package leetcode_题库;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/8/20 14:18
 */
public class _19_删除链表的倒数第N个结点 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode n = removeNthFromEnd(head,3);
        while (n!=null){
            System.out.print(n.val);
            n = n.next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        //若head为空，返回null
        if (head == null){
            return null;
        }
        //定义快慢指针
        ListNode fast = head,slow = head;
        //让快指针先走n步
        while (n-- > 0){
            fast = fast.next;
        }
        //若fast为空，说明删除首结点，返回首结点.next即可
        if (fast==null){
            return head.next;
        }
        //此时，快指针不为空，若快指针的下一个不为空，慢指针和快指针同时走
        //为什么要判断下一个结点？因为我们要让慢指针停留在待删除结点的前一结点
        while (fast.next!=null){
            fast = fast.next;
            slow = slow.next;
        }
        //快指针走到尽头，慢指针所在结点的下一结点就是要被删除的结点，直接slow.next = slow.next.next即可
        slow.next = slow.next.next;
        //返回头结点
        return head;
        /*
            > 2022/08/20 14:50:13
            解答成功:
                执行耗时:0 ms,击败了100.00% 的Java用户
                内存消耗:39.4 MB,击败了86.32% 的Java用户
        */
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
